from django.shortcuts import render
from django.http import HttpResponse
from goods.models import GoodsCategory
from goods.models import GoodsInfo
from django.core.paginator import Paginator

# Create your views here.
def purchase_index(request):
    #1. 查询商品分类
    categories=GoodsCategory.objects.all()

    #2. 从每个分类中获取四个商品
    for cag in categories:
        cag.goods_list = cag.goodsinfo_set.order_by('-id')[:4]

    #3. 获取购物车里所有的商品
    cart_goods_list=[]
    cart_goods_count=0
    for goods_id,goods_num in request.COOKIES.items():
        if not goods_id.isdigit():
            continue
        cart_goods = GoodsInfo.objects.get(id=goods_id)
        cart_goods.goods_num=int(goods_num)
        cart_goods_list.append(cart_goods)
        cart_goods_count+=int(goods_num)
    
    context={'categories':categories,'cart_goods_list':cart_goods_list,'cart_goods_count':cart_goods_count}
    return render(request,'purchase_index.html',context)

def detail(request):
    #1. 商品分类数据
    categories=GoodsCategory.objects.all()

    #2. 购物车数据
    cart_goods_list=[]
    cart_goods_count=0
    for goods_id,goods_num in request.COOKIES.items():
        if not goods_id.isdigit():
            continue
        cart_goods=GoodsInfo.objects.get(id=goods_id)
        cart_goods.goods_num=int(goods_num)
        cart_goods_list.append(cart_goods)
        cart_goods_count+=int(goods_num)

    #3. 当前显示商品数据
    goods_id=request.GET.get('id',1)
    goods_data=GoodsInfo.objects.get(id=goods_id)

    context={'categories': categories,'goods_data': goods_data,'cart_goods_list': cart_goods_list,'cart_goods_count': cart_goods_count}
    return render(request,'detail.html',context)

def goods(request):
    '''商品分类页面'''
    cag_id=request.GET.get('cag',1)
    page_id = request.GET.get('page', 1)
    #1. 当前分类下的所有商品
    current_cag=GoodsCategory.objects.get(id=cag_id)
    goods_data=GoodsInfo.objects.filter(goods_cag=current_cag)
    paginator = Paginator(goods_data, 12)
    page_data = paginator.page(page_id)
    #2. 所有分类
    categories=GoodsCategory.objects.all()
    #3. 购物车
    cart_goods_list=[]
    cart_goods_count=0
    for goods_id,goods_num in request.COOKIES.items():
        if not goods_id.isdigit():
            continue
        cart_goods=GoodsInfo.objects.get(id=goods_id)
        cart_goods.goods_num=int(goods_num)
        cart_goods_list.append(cart_goods)
        cart_goods_count+=int(goods_num)
    
    context={'current_cag':current_cag,'categories':categories,'cart_goods_list':cart_goods_list,'cart_goods_count':cart_goods_count,'paginator': paginator,'cag_id': cag_id,'page_data': page_data}
    return render(request,'goods.html',context)
